from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import json
from flask import current_app

db = SQLAlchemy()

class Conversation(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False, default="新对话")
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    messages = db.relationship('Message', backref='conversation', lazy=True, cascade='all, delete-orphan')
    
    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'message_count': len(self.messages)
        }

class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    conversation_id = db.Column(db.Integer, db.ForeignKey('conversation.id'), nullable=False)
    role = db.Column(db.String(20), nullable=False)  # 'user' or 'assistant'
    content = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def to_dict(self):
        return {
            'id': self.id,
            'role': self.role,
            'content': self.content,
            'created_at': self.created_at.isoformat()
        }

class Setting(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    key = db.Column(db.String(50), unique=True, nullable=False)
    value = db.Column(db.Text, nullable=False)
    
    @staticmethod
    def get_value(key, default=None):
        # 确保在应用上下文中执行查询
        if not current_app or not hasattr(current_app, 'app_context'):
            # 如果没有应用上下文，创建一个临时上下文
            from app import create_app
            app = create_app()
            with app.app_context():
                setting = Setting.query.filter_by(key=key).first()
                return setting.value if setting else default
        else:
            setting = Setting.query.filter_by(key=key).first()
            return setting.value if setting else default
    
    @staticmethod
    def set_value(key, value):
        # 确保在应用上下文中执行操作
        if not current_app or not hasattr(current_app, 'app_context'):
            # 如果没有应用上下文，创建一个临时上下文
            from app import create_app
            app = create_app()
            with app.app_context():
                setting = Setting.query.filter_by(key=key).first()
                if setting:
                    setting.value = value
                else:
                    setting = Setting(key=key, value=value)
                    db.session.add(setting)
                db.session.commit()
                return setting
        else:
            setting = Setting.query.filter_by(key=key).first()
            if setting:
                setting.value = value
            else:
                setting = Setting(key=key, value=value)
                db.session.add(setting)
            db.session.commit()
            return setting